package thread;

import java.text.SimpleDateFormat;
import java.util.Date;

//可运行的任务
public class Test2_Runnable {
    public static void main(String[] args) {
        //创建一个线程 绑定任务
        ShowTimeTask timeTask = new ShowTimeTask();
        Thread t = new Thread(timeTask);
        t.start();

        Runnable task2 = new InnerShowTimeTask();
        Thread t2 = new Thread(task2);
        t2.start();

        //匿名内部类
        new Thread(new Runnable() {
            private boolean flag;
            @Override
            public void run() {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM日 hh:mm:ss");
                Date d = null;
                while (!flag){
                    d = new Date();
                    System.out.println(Thread.currentThread().getName()+"time: "+simpleDateFormat.format(d));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();


        //因为Runnable接口上有@FunctionalInterface注解 表示这个接口支持lambda写法
        Thread t4 = new Thread(()->{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM日 hh:mm:ss");
            Date d = null;
            while (true){
                d = new Date();
                System.out.println(Thread.currentThread().getName()+"time: "+simpleDateFormat.format(d));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t4.start();
    }

    static class InnerShowTimeTask implements Runnable{
        private boolean flag;
        @Override
        public void run() {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM日 hh:mm:ss");
            Date d = null;
            while (!flag){
                d = new Date();
                System.out.println(Thread.currentThread().getName()+"time: "+simpleDateFormat.format(d));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

//任务类  -》他需要和线程绑定
class ShowTimeTask implements Runnable{
    private boolean flag;
    @Override
    public void run() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM日 hh:mm:ss");
        Date d = null;
        while (!flag){
            d = new Date();
            System.out.println(Thread.currentThread().getName()+"time: "+simpleDateFormat.format(d));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}